module(...,package.seeall)
require 'zdc.doc'

local _chglog = {}
local _mtkey = {}
local _chglog_mt = {
	__metatable = _mtkey,
	__index = _chglog
}

function new()
	local n = setmetatable({_d={},_c={},_a={}},_chglog_mt)
	return n
end

function _chglog:_noempty()
	return #self._d~=0 or #self._a~=0 or next(self._c)
end

function _chglog:_add(n)
	table.insert(self._a,n)
end

function _chglog:_del(n)
	table.insert(self._d,n)
end

function _chglog:_chg(n,t)
	self._c[n]=t
end

function _chglog:_gettable()
	if self._ptable then return self._ptable end
	self._ptable={label=self.label}
	local t={}
	for i,v in ipairs(self._d) do
		t[v.__id]=v:_valid_sub_to_table()
	end
	self._ptable.del=t
	t={}
	for i,v in ipairs(self._a) do
		t[v.__id]=v:_valid_to_table()
	end
	self._ptable.add=t
	t={}
	for i,v in pairs(self._c) do
		t[i.__id]=v
	end
	self._ptable.chg=t
	return self._ptable
end
function _chglog:tostring()
	local strbuf=zdc.doc.newStrStack()
	local app=zdc.doc.addString
	app(strbuf,'\ndel [')
	for k,v in ipairs(self._d) do
		app(strbuf,v.__id .. ' ')
	end
	app(strbuf,']\nadd [')
	for k,v in ipairs(self._a) do
		app(strbuf,v.__id .. ' ')
	end
	app(strbuf,']\nchg [')
	for k,v in pairs(self._c) do
		if next(v.chg) then
			app(strbuf,'\n* ' .. k.__id .. ' ')
			for m,n in pairs(v.chg) do
				if type(n) == 'boolean' then
					n = n and 'true' or 'false'
				end
				app(strbuf,m .. ' '..(n or ''))
			end
		end
		if next(v.del) then
			app(strbuf,'\n- ' .. k.__id)
			for m,n in pairs(v.del) do
				if type(n) == 'boolean' then
					n = n and 'true' or 'false'
				end
				app(strbuf,m .. ' '..(n or ''))
			end
		end
	end
	app(strbuf,']\n')
	return table.concat(strbuf)
end

